package org.monkey.example.order.service.impl;

import cn.hutool.core.util.StrUtil;
import io.seata.spring.annotation.GlobalTransactional;
import org.monkey.example.order.dao.OrderDao;
import org.monkey.example.order.entity.dto.OrderDto;
import org.monkey.example.order.entity.form.OrderForm;
import org.monkey.example.order.entity.form.PayForm;
import org.monkey.example.order.entity.po.OrderPo;
import org.monkey.example.order.provider.PayServiceProvider;
import org.monkey.example.order.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class OrderServiceImpl implements OrderService {

  @Autowired
  OrderDao orderDao;
  @Autowired
  PayServiceProvider payServiceProvider;

  @GlobalTransactional
  @Override
  public OrderDto save(OrderForm orderForm) {
    OrderDto orderDto = new OrderDto(orderForm);
    if (orderDto.getId() == null) {
      orderDto.setOrderNumber(StrUtil.uuid());
    }
    OrderPo orderPo = new OrderPo(orderDto);
    orderDao.insert(orderPo);
    payServiceProvider.payAmount(
        PayForm.builder().accountId(orderForm.getAccountId()).amount(orderForm.getAmount())
            .build());
    return new OrderDto(orderPo);
  }
}
